package com.fyb.basic.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量 挣车位（可伸缩）
 * // 假设存在6俩车 3个车位
 *
 * @author geng
 * @date 2021-08-21 22:34
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        //sync = new NonfairSync(permits);
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire(); // 先获得许可
                    System.out.println(Thread.currentThread().getName() + "\t 抢到了一个车位");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName() + "\t 离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release(); // 释放许可
                }
            }, String.valueOf(i + 1)).start();
        }

    }
}
